import axios from 'axios'
import { getToken } from '@/utils/store'

import { Loading } from 'element-ui'

import JSONbig from 'json-bigint'

let loadingInstance
// http://toutiao-app.itheima.net/
// 'http://ttapi.research.itcast.cn/'
const BASE_URL = 'http://api-toutiao-web.itheima.net/'
const myAxios = axios.create({
  baseURL: BASE_URL,
  transformResponse: [function (data) {
    // Do whatever you want to transform the data
    // console.log('transformResponse', data)
    try {
      return JSONbig.parse(data)
    } catch (err) {
      console.log('JSONbig转换出错', err)
      return data
    }
  }]
})

// Add a request interceptor
myAxios.interceptors.request.use(function (config) {
  // Do something before request is sent
  // console.log(config)
  loadingInstance = Loading.service({ text: '努力加载中...', background: 'rgba(0,0,0,.6)' })
  // 排除登录接口
  if (!config.url.includes('/authorizations')) {
    config.headers.Authorization = `Bearer ${getToken().token}`
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
myAxios.interceptors.response.use(function (response) {
  // Do something with response data
  setTimeout(function () { loadingInstance.close() }, 800)
  return response
}, function (error) {
  loadingInstance.close()
  // Do something with response error
  return Promise.reject(error)
})

export default myAxios
